<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/12/28
 * Time: 9:56
 */

namespace AuctionBack\Logic;

use AuctionBack\Logic\CarReportLogic;
use AuctionBack\Logic\CarOwnerLogic;
use AuctionBack\Logic\TransferLogic;
use AuctionCore\CarResource\CarModel;
use AuctionBack\Logic\OrderLogic;


class ProceduresLogic
{

    /**
     * 编号
     *
     * @var
     */
    protected $id;

    /**
     * @var \Model|\Think\Model
     */
    protected $model;

    /**
     * ProceduresLogic constructor.
     * @param $id
     */
    public function __construct($id)
    {
        $this->id = $id;
        $this->model = D('Procedures', 'Model');
    }

    /**
     * 手续添加
     *
     * @param $data
     * @return mixed
     */
    public static function add($data)
    {
        $lastData = [
            'order_id' => $data['order_id'],
            'car_id' => $data['car_id'],
            'sid' => $data['sid'],
            'emp_id' => $data['emp_id'],
            'emp_name' => $data['emp_name'],
            'created_time' => $data['created_time'],
        ];
        return D('Procedures', 'Model')->add($lastData);
    }

    /**
     * 手续列表
     *
     * @param int $page 当前第几页
     * @param int $size 每页条数
     * @param $params 参数
     * @return array
     */
    public static function getList($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;

        $uploadStatus = $params['upload_status'];
        $map = self::make_params($params);

        if ($map === false) {
            return [
                'total' => 0,
                'list' => [],
            ];
        }

        $order = '';
        if ($uploadStatus == 0) {
            $order = 'created_time desc';
        }

        if ($uploadStatus == 1) {
            $order = 'upload_time desc';
        }

        $total = D('Procedures', 'Model')->where($map)->count();
        $list = D('Procedures', 'Model')->where($map)->page($page)->order($order)->limit($size)->select();

        $carModelObj = new CarModel();
        foreach ($list as $key => $values) {
            $carId = $values['car_id'];

            $carInfo = CarReportLogic::getCarInfo(['car_id' => $carId]);

            $brand = $carModelObj->get_model_by_id($carInfo['brand_id'], 'brand');
            $series = $carModelObj->get_model_by_id($carInfo['series_id'], 'series');
            $model = $carModelObj->get_model_by_id($carInfo['model_id']);
            $list[$key]['car_model'] = $brand['name'] . $series['name'] . $model['name']; //车型
            //车牌号
            $list[$key]['plate_number'] = C("PLATE_PREFIX." . $carInfo['plate_prefix']) . $carInfo['plate_suffix'];
            //渠道来源
            $list[$key]['come_from'] = CarModel::getComeFromByCarId($carInfo['car_id']);

            $ownerId = $carInfo['owner_id'];
            $carOwner = CarOwnerLogic::getCarOwnerByMap(['owner_id' => $ownerId]);
            $list[$key]['car_owner_name'] = $carOwner['seller_name']; //车主名称
            $list[$key]['car_owner_phone'] = $carOwner['phone']; // 车主电话
            $list[$key]['car_sno'] = $carInfo['sno'];//车辆编号

            $orderId = $values['order_id'];
            $transferInfo = TransferLogic::getTransferInfoByOrderId($orderId);

            $list[$key]['transfer_to'] = C("TRANSFER_TO." . $transferInfo['transfer_to']);

            //print_r($transferInfo['transfer_to']);die();
        }

        return [
            'total' => $total,
            'list' => $list,
        ];
    }

    public function make_params($params)
    {
        $uploadStatus = $params['upload_status'];
        $map = [
            'upload_status' => ['eq', $uploadStatus],
        ];

        $carMap = [];

        $mapSids = [];
        if (!empty($params['location_area'])) {
            $carMap['location_area'] = ['in', $params['location_area']];
            $CarsInfo = CarReportLogic::getCarInfos($carMap);
            foreach ($CarsInfo as $key => $value) {
                $mapSids[] = $value['sid'];
            }
            if (empty($mapSids)) {
                return false;
            }
        }
        $sno = $params['sno'];//车辆编号

        if (!empty($sno)) {
            $carMap['sno'] = $sno;
            $CarsInfo = CarReportLogic::getCarInfos($carMap);
            $mapSidsTow = [];
            foreach ($CarsInfo as $key => $value) {
                $mapSidsTow[] = $value['sid'];
            }

            if (empty($mapSids)) {
                $mapSids = $mapSidsTow;
            } else {
                $mapSids = array_intersect($mapSids, $mapSidsTow);
            }

            if (empty($mapSids)) {
                return false;
            }
        }
        $carPlateNumber = $params['car_plate_number']; //车牌号
        if (!empty($carPlateNumber)) {
            $where = [];
            $car_plate_number = trim($carPlateNumber);
            $car_plate_number_first = mb_substr($car_plate_number, 0, 1, 'UTF8');
            $car_plate_number_last = mb_substr($car_plate_number, 1, 7, 'UTF8');
            $plate_prefix = array_search($car_plate_number_first, C('PLATE_PREFIX'));
            $plate_suffix = substr($car_plate_number, 1);
            $where['plate_prefix'] = array('eq', $plate_prefix);
            if ($car_plate_number_last) {
                $where['plate_suffix'] = array('eq', $car_plate_number_last);
            }


            $CarsInfo = CarReportLogic::getCarInfos($where);

            $mapSidsNew = [];
            foreach ($CarsInfo as $key => $value) {
                $mapSidsNew[] = $value['sid'];
            }
            if (empty($mapSids)) {
                $mapSids = $mapSidsNew;
            } else {
                $mapSids = array_intersect($mapSids, $mapSidsNew);
            }
            if (empty($mapSids)) {
                return false;
            }
        }

        if (!empty($mapSids)) {
            $map['sid'] = ['in', $mapSids];
        }

        return $map;
    }

    public function detail()
    {
        $map = [
            'id' => $this->id
        ];
        $proceduresInfo = $this->model->where($map)->find();
        $carId = $proceduresInfo['car_id'];

        $detail = D('Cars', 'Model')->where(['car_id' => $carId])->find();

        //print_r($detail);die();
        //RefundModel::
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($detail['brand_id'], 'brand');
        $series = $cm->get_model_by_id($detail['series_id'], 'series');
        $model = $cm->get_model_by_id($detail['model_id']);

        $proceduresInfo['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $proceduresInfo['car_color'] = C('CAR_COLOR.' . $detail['car_color']);
        $proceduresInfo['emission'] = C('INT_EMISSION_STD.' . $detail['emission']);
        $proceduresInfo['plate_prefix'] = C('PLATE_PREFIX.' . $detail['plate_prefix']);
        $proceduresInfo['plate_suffix'] = $detail['plate_suffix'];
        $proceduresInfo['pointer_mileage'] = formatMileage($detail['pointer_mileage']);
        $proceduresInfo['transfer_limit'] = C('TRANSFER_LIMIT.' . $detail['transfer_limit']);
        $proceduresInfo['comefrom'] = CarModel::getComeFromByCarId($carId);
        $proceduresInfo['sno'] = $detail['sno'];
        $proceduresInfo['first_reg_date'] = $detail['first_reg_date'];
        $proceduresInfo['composite_state'] = $detail['composite_state'];
        $proceduresInfo['accident_level'] = $detail['accident_level'];
        $proceduresInfo['vin'] = $detail['vin'];

        $ownerId = $detail['owner_id'];
        $ownerInfo = D('CarOwner', 'Model')->where(['owner_id', $ownerId])->find();
        $proceduresInfo['seller_name'] = $ownerInfo['seller_name'];
        $proceduresInfo['phone'] = $ownerInfo['phone'];
        $addr = new \AuctionCore\Other\Address();
        //echo $ownerInfo['location_area'];die();
        $proceduresInfo['first_reg_city'] = $addr->get_name_by_code($ownerInfo['first_reg_city']);
        $proceduresInfo['location_area'] = $addr->get_name_by_code($ownerInfo['location_area']);

        $orderId = $proceduresInfo['order_id'];
        $transferInfo = TransferLogic::getTransferInfoByOrderId($orderId);
        $proceduresInfo['transfer_to'] = C("TRANSFER_TO." . $transferInfo['transfer_to']); //车辆落户


        $returnInfo = M('car_return_log')->where(['order_id' => $orderId])->find();
        $proceduresInfo['invoice'] = $returnInfo['invoice']; //开票要求

        $orderObj = new OrderLogic($orderId);
        $orderInfo = $orderObj->detail();
        $proceduresInfo['transfer_type'] = C('TRANSFER_TYPE')[$orderInfo['transfer_type']];//过户要求
        $proceduresInfo['order_no'] = $orderInfo['order_no'];//拍单编号

        $beforeTransfer = M('setting')->where(['name' => 'BEFORE_TRANSFER_PROCEDURES'])->find();
        $proceduresInfo['before_transfer_procedures'] = json_decode($beforeTransfer['value'], true); //过户前手续

        $proceduresInfo['proceduresFile'] = M('transfer_img')->where(['order_id' => $orderId])->select();
        //print_r(count($proceduresInfo));die();
        $host = get_content_cdnurl();
        //$url = $host . $aliObject;
        $proceduresInfo['host'] = $host;

        $afterTransfer = M('setting')->where(['name' => 'AFTER_TRANSFER_PROCEDURES'])->find();
        $proceduresInfo['after_transfer_procedures'] = json_decode($afterTransfer['value'], true); //过户后手续

        return $proceduresInfo;
    }

    public function save($data)
    {
        $map = [
            'id' => $this->id
        ];
        $result = $this->model->where($map)->save($data);
        return $result;

    }
}